﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using ZP.Common;
using ZP.DTO.Common;
using ZP.DTO.fz_sys_role;
using ZP.IBLL;
using ZP.IDAL;
using ZP.Model;
using Z.EntityFramework.Plus;

namespace ZP.BLL
{
    public partial class fz_sys_roleService : BaseService<fz_sys_role, int>, Ifz_sys_roleService
    {
        //public fz_sys_roleService(Ifz_sys_roleDAL _fz_sys_roleDAL, Ifz_sys_userDAL _fz_sys_userDAL)
        //{
        //    this._fz_sys_roleDAL = _fz_sys_roleDAL;
        //    this._fz_sys_userDAL = _fz_sys_userDAL;

        //    this._repository = _fz_sys_roleDAL;
        //}

        /// <summary>
        /// 获得所有的角色
        /// </summary>
        /// <returns></returns>
        public PageModel<fz_sys_roleResultDTO> GetSysRole(fz_sys_roleSearchDTO dto, bool isPaging = true)
        {
            PageModel<fz_sys_roleResultDTO> result = new PageModel<fz_sys_roleResultDTO>();
            Expression<Func<fz_sys_role, bool>> WhereLambda = (p => p.state == ZPFlagType.YES);
            if (null != dto)
            {
                if (!string.IsNullOrWhiteSpace(dto.SearchText))
                {
                    WhereLambda = WhereLambda.And(p => p.name.Contains(dto.SearchText) || p.code.Contains(dto.SearchText));
                }
            }

            Expression<Func<fz_sys_role, int>> OrderByLambda = (o => o.id);
            IQueryable<fz_sys_role> iquery;
            if (isPaging)
            {
                int total = 0;
                iquery = _repository.GetModelsByPage(dto.limit, dto.page, out total, WhereLambda, OrderByLambda, false);
                result.count = total;
            }
            else
            {
                iquery = _repository.GetModels(WhereLambda);
                result.count = iquery.Count();
            }

            result.data = Mapper.Map<List<fz_sys_role>, List<fz_sys_roleResultDTO>>(iquery.ToList());
            return result;
        }

        /// <summary>
        /// 保存角色信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public bool SaveSysRole(fz_sys_roleOperateDTO dto)
        {
            bool result = false;
            if (0 == dto.id || !dto.id.HasValue)
            {
                //判断是否已经存在角色名称和角色编码
                bool existsCount = _repository.GetModels(p => p.name == dto.name && p.state == ZPFlagType.YES).Any();
                if (existsCount)
                {
                    throw new Exception(TipsMessage.该角色名称已存在);
                }

                existsCount = _repository.GetModels(p => p.code == dto.code && p.state == ZPFlagType.YES).Any();
                if (existsCount)
                {
                    throw new Exception(TipsMessage.该角色编码已存在);
                }
                //新增
                var item = Mapper.Map<fz_sys_roleOperateDTO, fz_sys_role>(dto);
                item.state = ZPFlagType.YES;
                item.updatetime = DateTime.Now;
                _repository.Add(item);
                result = true;
                //result = Add_AutoSaveChanges(psie, item, out entity);
                //if (result)
                //{
                //    记录日志
                //    this.AddLog(psie, new LogData
                //    {
                //        CurrentLogType = LogType.ADD,
                //        LogDetails = "新增角色" + dto.name,
                //        OpratorName = dto.updater
                //    });
                //    psie.SaveChanges();
                //}
            }
            else
            {
                //判断是否已经存在角色名称和角色编码
                bool existsCount = _repository.GetModels(p => p.name == dto.name && p.id != dto.id && p.state == ZPFlagType.YES).Any();
                if (existsCount)
                {
                    throw new Exception(TipsMessage.该角色名称已存在);
                }

                existsCount = _repository.GetModels(p => p.code == dto.code && p.id != dto.id && p.state == ZPFlagType.YES).Any();
                if (existsCount)
                {
                    throw new Exception(TipsMessage.该角色编码已存在);
                }
                //修改
                fz_sys_role item = _repository.Find(dto.id.Value);
                dto.state = ZPFlagType.YES;
                dto.updatetime = DateTime.Now;
                Mapper.Map<fz_sys_roleOperateDTO, fz_sys_role>(dto, item);
                _repository.Update(item);
                result = true;
                //result = Modify_AutoSaveChanges(psie, item, out entity);
                //if (result)
                //{
                //    // 记录日志
                //    this.AddLog(psie, new LogData
                //    {
                //        CurrentLogType = LogType.MODIFY,
                //        LogDetails = "修改角色" + dto.name,
                //        OpratorName = dto.updater
                //    });
                //    psie.SaveChanges();
                //}
            }

            return result;
        }

        /// <summary>
        /// 删除角色信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public bool DeleteSysRole(List<fz_sys_roleOperateDTO> dto, UserLoginDTO loginUser)
        {
            bool result = false;
            var roleNames = "";
            if (dto != null && dto.Count > 0)
            {
                List<int> intIdsList = dto.Select(i => i.id.Value).ToList();
                //List<int> intIdsList = longIds.ConvertAll<int>(x => Convert.ToInt32(x));
                //查询角色下是否还存在用户，存在则不能删除
                var roleInUsers = _fz_sys_userDAL.GetModels(p => p.state == ZPFlagType.YES && intIdsList.Contains(p.roleId.Value)).ToList();
                foreach (fz_sys_user user in roleInUsers)
                {
                    roleNames += user.roleName + ",";
                }
                roleNames = roleNames.TrimEnd(',');
                if (!string.IsNullOrWhiteSpace(roleNames))
                {
                    throw new Exception(TipsMessage.这些角色下还存在用户 + roleNames);
                }
                var itemList = _repository.GetModels(p => intIdsList.Contains(p.id));
                //result = Delete_AutoSaveChanges(psie, itemList);
                //result = _repository.Delete(intIdsList.ToArray()) > 0;
                int resultCount = itemList.Update(p => new fz_sys_role { state = ZPFlagType.NO });
                result = resultCount > 0;
            }
            //if (result)
            //{
            //    // 记录日志
            //    this.AddLog(psie, new LogData
            //    {
            //        CurrentLogType = LogType.DELETE,
            //        LogDetails = "删除角色" + roleNames,
            //        OpratorName = loginUser.account
            //    });
            //    psie.SaveChanges();
            //}
            return result;
        }

    }
}
